package com.example.memo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.example.memo.Adapter.NoteAdapter;
import com.example.memo.Adapter.SearchAdapter;
import com.example.memo.db.NoteHelper;
import com.example.memo.entity.NoteInfo;
import com.example.memo.entity.UserInfo;

import java.util.List;

public class SearchFragment extends Fragment {
    private EditText et_search;
    private View rootView;
    private RecyclerView recyclerView;
    private List<NoteInfo> noteList;
    private NoteHelper noteHelper;
    private SearchAdapter searchAdapter;
    private LinearLayoutManager layoutManager;

    public SearchFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_search, container, false);
        initView(rootView);
        initData();
        return rootView;
    }

    private void initView(View rootView) {
        et_search = rootView.findViewById(R.id.et_search);
        recyclerView = rootView.findViewById(R.id.recyclerview);
        searchAdapter = new SearchAdapter();
        recyclerView.setAdapter(searchAdapter);
        noteHelper = new NoteHelper(getActivity());

        rootView.findViewById(R.id.tv_search).setOnClickListener(view -> {
            String content = et_search.getText().toString();
            if(!TextUtils.isEmpty(content)){
                noteList = noteHelper.search(content);
                searchAdapter.addNote(noteList);
            }else{
                searchAdapter.addNote(null);
            }
        });

        searchAdapter.setOnItemClickListener(position -> {
            Intent intent = new Intent(getActivity(),NotePage.class);
            if(noteList != null){
                intent.putExtra("noteInfo",noteList.get(position));
                startActivity(intent);
            }
        });
    }

    private void initData() {
        layoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(layoutManager);
    }
}